import React from "react";
import { Album, fetchData } from "./data";

interface AlbumsProps {
  artistId: string;
}
const Albums: React.FC<AlbumsProps> = ({ artistId }) => {
  const albums = use(fetchData(`/${artistId}/albums`));

  return (
    <ul>
      {albums?.map(album => (
        <li key={album.id}>
          {album.title} ({album.year})
        </li>
      ))}
    </ul>
  );
};

function use(
  promise?: Promise<Album[]> & { status?: "fulfilled" | "rejected" | "pending"; value?: Album[]; reason?: any }
) {
  if (promise?.status === "fulfilled") {
    return promise.value;
  } else if (promise?.status === "rejected") {
    throw promise.reason;
  } else if (promise?.status === "pending") {
    throw promise;
  } else {
    promise!.status = "pending";
    promise?.then(
      result => {
        promise.status = "fulfilled";
        promise.value = result;
      },
      reason => {
        promise.status = "rejected";
        promise.reason = reason;
      }
    );
    throw promise;
  }
}
export default Albums;
